<template>
  <view class="page">
    <uni-nav-bar
      :fixed="true"
      :statusBar="true"
      left-icon="left"
      title="编辑商品详情"
      @clickLeft="handleBack"
    >
      <template v-slot:right>
        <view class="save-btn" @click="handleSave">保存</view>
      </template>
    </uni-nav-bar>

    <view class="editor-container">
      <!-- 富文本编辑器工具栏 -->
      <view class="toolbar">
        <view class="toolbar-content toolbar-wrap">
          <!-- 文本样式 -->
          <view
            class="toolbar-item"
            :class="{ active: formats.bold }"
            @click="handleFormat('bold')"
          >
            <text class="icon-text bold">B</text>
          </view>
          <view
            class="toolbar-item"
            :class="{ active: formats.italic }"
            @click="handleFormat('italic')"
          >
            <text class="icon-text italic">I</text>
          </view>
          <view
            class="toolbar-item"
            :class="{ active: formats.underline }"
            @click="handleFormat('underline')"
          >
            <text class="icon-text underline">U</text>
          </view>
          <view
            class="toolbar-item"
            :class="{ active: formats.strike }"
            @click="handleFormat('strike')"
          >
            <text class="icon-text strike">S</text>
          </view>

          <view class="toolbar-divider"></view>

          <!-- 标题已移除 H1/H2/H3 -->

          <!-- 列表 -->
          <view
            class="toolbar-item"
            :class="{ active: formats.list === 'ordered' }"
            @click="handleList('ordered')"
          >
            <image
              class="icon-img"
              src="/static/icon/yxlb.png"
              mode="widthFix"
            />
          </view>
          <view
            class="toolbar-item"
            :class="{ active: formats.list === 'bullet' }"
            @click="handleList('bullet')"
          >
            <image
              class="icon-img"
              src="/static/icon/wxlb.png"
              mode="widthFix"
            />
          </view>

          <view class="toolbar-divider"></view>

          <!-- 对齐 -->
          <view
            class="toolbar-item"
            :class="{ active: formats.align === 'left' }"
            @click="handleAlign('left')"
          >
            <image
              class="icon-img"
              src="/static/icon/zdq.png"
              mode="widthFix"
            />
          </view>
          <view
            class="toolbar-item"
            :class="{ active: formats.align === 'center' }"
            @click="handleAlign('center')"
          >
            <image
              class="icon-img"
              src="/static/icon/jzdq.png"
              mode="widthFix"
            />
          </view>
          <view
            class="toolbar-item"
            :class="{ active: formats.align === 'right' }"
            @click="handleAlign('right')"
          >
            <image
              class="icon-img"
              src="/static/icon/ydq.png"
              mode="widthFix"
            />
          </view>

          <view class="toolbar-divider"></view>

          <!-- 颜色 -->
          <view class="toolbar-item" @click="showColorPicker = true">
            <text
              class="icon-text"
              :style="{ color: formats.color || '#000000' }"
              >A</text
            >
          </view>

          <view class="toolbar-divider"></view>

          <!-- 图片上传 -->
          <view class="toolbar-item" @click="handleInsertImage">
            <uni-icons type="image" size="20" color="#333" />
          </view>

          <view class="toolbar-divider"></view>

          <!-- 清空 -->
          <view class="toolbar-item" @click="handleClear">
            <text class="icon-text">清空</text>
          </view>
        </view>
      </view>

      <!-- 颜色选择器 -->
      <view class="color-picker" v-if="showColorPicker">
        <view class="color-picker-header">
          <text>选择文字颜色</text>
          <text class="close-btn" @click="showColorPicker = false">✕</text>
        </view>
        <view class="color-list">
          <view
            v-for="color in colorList"
            :key="color"
            class="color-item"
            :style="{ backgroundColor: color }"
            @click="handleColor(color)"
          ></view>
        </view>
      </view>

      <!-- 富文本编辑器 -->
      <editor
        id="editor"
        class="ql-container"
        placeholder="请输入商品详情..."
        :show-img-size="true"
        :show-img-toolbar="true"
        :read-only="false"
        @ready="onEditorReady"
        @input="onEditorInput"
        @statuschange="onSelectionChange"
      ></editor>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";
import { useEditorStore } from "@/store/modules/editor";
import { uploadToOss } from "@/utils/oss";

// 使用 store
const editorStore = useEditorStore();

// 编辑器上下文
const editorCtx = ref(null);
const content = ref("");
// 当前格式状态
const formats = ref({});

// 颜色选择器
const showColorPicker = ref(false);
const colorList = [
  "#000000",
  "#333333",
  "#666666",
  "#999999",
  "#e74c3c",
  "#e67e22",
  "#f39c12",
  "#f1c40f",
  "#2ecc71",
  "#1abc9c",
  "#3498db",
  "#9b59b6",
  "#34495e",
  "#95a5a6",
  "#ffffff",
];

// 编辑器准备完成
const onEditorReady = () => {
  uni
    .createSelectorQuery()
    .select("#editor")
    .context((res) => {
      editorCtx.value = res.context;

      // 如果有之前的内容，加载进来
      if (editorStore.richText) {
        editorCtx.value.setContents({
          html: editorStore.richText,
        });
      }
    })
    .exec();
  // H5 平台强制允许编辑区域选中
  // #ifdef H5
  setTimeout(() => {
    const el = document.querySelector("#editor");
    if (el) {
      el.style.webkitUserSelect = "text";
      el.style.userSelect = "text";
    }
  }, 0);
  // #endif
};

// 监听编辑器内容变化
const onEditorInput = (e) => {
  content.value = e.detail.html;
};

// 同步选区格式状态
const onSelectionChange = (e) => {
  formats.value = e.detail;
};

// 格式化文本
const handleFormat = (format) => {
  if (!editorCtx.value) return;

  editorCtx.value.format(format);
};

// 设置标题
const handleHeader = (level) => {
  if (!editorCtx.value) return;

  editorCtx.value.format("header", level);
};

// 设置列表
const handleList = (type) => {
  if (!editorCtx.value) return;

  editorCtx.value.format("list", type);
};

// 设置对齐方式
const handleAlign = (align) => {
  if (!editorCtx.value) return;

  editorCtx.value.format("align", align);
};

// 设置文字颜色
const handleColor = (color) => {
  if (!editorCtx.value) return;

  editorCtx.value.format("color", color);
  showColorPicker.value = false;

  uni.showToast({
    title: "颜色已设置",
    icon: "none",
  });
};

// 插入图片
const handleInsertImage = () => {
  if (!editorCtx.value) {
    uni.showToast({
      title: "编辑器未准备好",
      icon: "none",
    });
    return;
  }

  uni.chooseImage({
    count: 1,
    sizeType: ["compressed"],
    sourceType: ["album", "camera"],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0];

      // 显示上传进度
      uni.showLoading({
        title: "上传中 0%",
        mask: true,
      });

      try {
        // 上传图片到 OSS
        const result = await uploadToOss(tempFilePath, {
          prefix: "goods/editor/",
          onProgress: (progress) => {
            // 更新上传进度
            uni.showLoading({
              title: `上传中 ${progress}%`,
              mask: true,
            });
          },
        });

        // 插入图片到编辑器
        editorCtx.value.insertImage({
          src: result.url,
          alt: "商品图片",
          width: "100%",
          success: () => {
            uni.hideLoading();
            uni.showToast({
              title: "图片插入成功",
              icon: "none",
            });
          },
          fail: (error) => {
            console.error("插入图片失败:", error);
            uni.hideLoading();
            uni.showToast({
              title: "图片插入失败",
              icon: "none",
            });
          },
        });
      } catch (error) {
        uni.hideLoading();
        console.error("上传图片失败:", error);
        uni.showToast({
          title: error.message || "上传失败，请重试",
          icon: "none",
        });
      }
    },
    fail: (error) => {
      console.error("选择图片失败:", error);
      uni.showToast({
        title: "选择图片失败",
        icon: "none",
      });
    },
  });
};

// 清空内容
const handleClear = () => {
  uni.showModal({
    title: "提示",
    content: "确定要清空所有内容吗？",
    success: (res) => {
      if (res.confirm && editorCtx.value) {
        editorCtx.value.clear();
        content.value = "";
      }
    },
  });
};

// 保存内容
const handleSave = () => {
  if (!content.value || content.value.trim() === "<p><br></p>") {
    uni.showToast({
      title: "请输入内容",
      icon: "none",
    });
    return;
  }

  // 保存到 store
  editorStore.setRichText(content.value);

  uni.showToast({
    title: "保存成功",
    icon: "none",
  });

  setTimeout(() => {
    uni.navigateBack();
  }, 500);
};

// 返回
const handleBack = () => {
  if (content.value && content.value !== editorStore.richText) {
    uni.showModal({
      title: "提示",
      content: "内容未保存，确定要退出吗？",
      success: (res) => {
        if (res.confirm) {
          uni.navigateBack();
        }
      },
    });
  } else {
    uni.navigateBack();
  }
};

onLoad(() => {
  // 页面加载
});

onUnload(() => {
  // 页面卸载
});
</script>

<style scoped lang="scss">
.page {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.save-btn {
  color: #007aff;
  font-size: 28rpx;
  padding: 0 20rpx;
}

.editor-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  //   padding: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
}

.toolbar {
  background-color: transparent;
  //   padding: 16rpx 20rpx;
}

.toolbar-content {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 12rpx;
  padding: 12rpx;
  width: 100%;
  background-color: #ffffff;
  border: 1px solid #f0f0f0;
  //   border-radius: 16rpx;
  //   box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.06);
}

.toolbar-item {
  flex-shrink: 0;
  width: 64rpx;
  height: 64rpx;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  //   border-radius: 50%;
  background-color: #ffffff;
  border: 1px solid #eeeeee;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.04);
  transition: transform 0.12s ease, background-color 0.12s ease,
    box-shadow 0.12s ease;

  &:active {
    background-color: #f7f7f7;
    transform: scale(0.96);
    box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.06);
  }

  &:last-child {
    margin-right: 0;
  }

  &.active {
    background-color: #e8f0ff;
    border-color: #c6dbff;
    box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.18);
  }
}

.toolbar-divider {
  display: none;
}

.icon-text {
  font-size: 26rpx;
  font-weight: 700;
  color: #333;

  &.bold {
    font-weight: 900;
  }

  &.italic {
    font-style: italic;
  }

  &.underline {
    text-decoration: underline;
  }

  &.strike {
    text-decoration: line-through;
  }
}

.icon-img {
  width: 36rpx;
  height: 36rpx;
}

.color-picker {
  position: absolute;
  top: 120rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
  max-width: 600rpx;
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
  z-index: 1000;
  padding: 20rpx;
}

.color-picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  font-size: 28rpx;
  font-weight: bold;

  .close-btn {
    font-size: 36rpx;
    color: #999;
    padding: 0 10rpx;
  }
}

.color-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.color-item {
  width: 60rpx;
  height: 60rpx;
  border-radius: 8rpx;
  border: 2px solid #eee;

  &:active {
    transform: scale(0.95);
  }
}

.ql-container {
  flex: 1;
  width: 100%;
  padding: 20rpx;
  box-sizing: border-box;
  background-color: #fff;
  user-select: text; /* H5 允许文字选中 */
}
</style>
